package cn.ac.jaas.isc.vegetable.common.security.component;

import cn.ac.jaas.isc.vegetable.common.core.constant.SecurityConstants;
import cn.ac.jaas.isc.vegetable.common.core.util.KeyStrResolver;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author 张高昌
 * @date 2022/4/23 14:05
 * @description: redis token store 自动配置
 */
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
public class VegetableTokenStoreAutoConfiguration {

    private final KeyStrResolver resolver;

    private final RedisConnectionFactory connectionFactory;

    @Bean
    public TokenStore tokenStore() {
        VegetableRedisTokenStore tokenStore = new VegetableRedisTokenStore(connectionFactory, resolver);
        tokenStore.setPrefix(SecurityConstants.VEGETABLE_PREFIX + SecurityConstants.OAUTH_PREFIX);
        tokenStore.setAuthenticationKeyGenerator(new DefaultAuthenticationKeyGenerator() {
            @Override
            public String extractKey(OAuth2Authentication authentication) {
                // 增加租户隔离部分 租户ID:原生计算值
                return resolver.extract(super.extractKey(authentication), StrUtil.COLON);
            }
        });
        return tokenStore;
    }
}
